/*! ******************************************************************************
 *
 * Created on 2022年6月11日
 *
 * Copyright(c) YuZhou Big Data Laboratory CO.,Ltd, 2022.  All rights reserved.
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/
package org.pentaho.di.ui.spoon.navigation.design.classification;

import org.pentaho.di.core.plugins.JobEntryPluginType;
import org.pentaho.di.core.plugins.StepPluginType;
import org.yzbdl.lanius.core.plugins.service.CategoryService;
import org.yzbdl.lanius.core.plugins.service.ClassificationService;
import org.yzbdl.lanius.core.plugins.service.PluginService;

/**
 * 插件类别数据业务
 *
 * @author hs@yzbdl.ac.cn
 * @version 1.0
 * @date 2019-06-11 10:40
 */
public class InitThread implements Runnable {

    private ClassificationService classificationService = ClassificationService.getInstance();
    private CategoryService categoryService = CategoryService.getInstance();
    private PluginService pluginService = PluginService.getInstance();

    // private ClassificationDao classificationDao = ClassificationDao.getInstance();

    // private CategoryDao categoryDao = CategoryDao.getInstance();
    //
    // private PluginDao pluginDao = PluginDao.getInstance();
    //
    // private PluginCategoryDao pluginCategoryDao = PluginCategoryDao.getInstance();

    @Override
    public void run() {
        try {
            initTransCommonly();
            //// initTransDefault();
            //
            initJobCommonly();
            //// initJobDefault();
            //
            // EventContext.publish(new TransInitedEvent(null));
            // EventContext.publish(new JobInitedEvent(null));
            //
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化转换-->常用
     *
     * @throws Exception
     */
    private void initTransCommonly() throws Exception {
        classificationService.addCommonly(StepPluginType.class);
    }

    // /**
    // * 初始化转换-->本地
    // *
    // * @throws Exception
    // */
    // private void initTransDefault() throws Exception {
    // // 检查添加转换本地
    // ClassificationEntity entity = classificationService.addDefault(StepPluginType.class);
    // PluginRegistry registry = PluginRegistry.getInstance();
    // List<PluginInterface> basePlugins = registry.getPlugins(StepPluginType.class);
    // // 获取分类
    // List<String> categories = registry.getCategories(StepPluginType.class);
    // // 类别循环处理
    // for (String category : categories) {
    // try {
    // CategoryEntity categoryEntity = categoryService.addCategory(category, entity);
    //
    // // 获取分类下面的插件
    // List<PluginInterface> plugins = basePlugins.parallelStream()
    // .filter(basePlugin -> basePlugin.getCategory().equalsIgnoreCase(category))
    // .sorted(Comparator.comparing(PluginInterface::getName)).collect(Collectors.toList());
    // addPlugins(plugins, categoryEntity);
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // }

    // /**
    // * 初始化转换-->云端
    // *
    // * @throws Exception
    // */
    // private ClassificationEntity initTransMarket() throws Exception {
    // return classificationService.addMarket(StepPluginType.class);
    // }

    /**
     * 初始化作业-->常用
     */
    private void initJobCommonly() throws Exception {
        // 检查添加作业常用
        classificationService.addCommonly(JobEntryPluginType.class);
    }

    // /**
    // * 初始化作业-->本地
    // */
    // private void initJobDefault() throws Exception {
    // // 检查添加作业本地
    // ClassificationEntity entity = classificationService.addDefault(JobEntryPluginType.class);
    //
    // PluginRegistry registry = PluginRegistry.getInstance();
    // List<PluginInterface> basePlugins = registry.getPlugins(JobEntryPluginType.class);
    // // 获取分类
    // List<String> categories = registry.getCategories(JobEntryPluginType.class);
    // // 类别循环处理
    // for (String category : categories) {
    // try {
    // CategoryEntity categoryEntity = categoryService.addCategory(category, entity);
    //
    // // 获取分类下面的插件
    // List<PluginInterface> plugins = basePlugins.parallelStream()
    // .filter(basePlugin -> basePlugin.getCategory().equalsIgnoreCase(category))
    // .sorted(Comparator.comparing(PluginInterface::getName)).collect(Collectors.toList());
    //
    // addPlugins(plugins, categoryEntity);
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // }
    //
    // /**
    // * 初始化作业-->云端
    // */
    // private ClassificationEntity initJobMarket() throws Exception {
    // // 检查添加作业云端
    // return classificationService.addMarket(JobEntryPluginType.class);
    // }
    //
    // private void addPlugins(List<PluginInterface> basePlugins, CategoryEntity categoryEntity) {
    // final int categoryId = categoryEntity.getId();
    // // 插件循环处理
    // for (PluginInterface plugin : basePlugins) {
    // try {
    // String pluginStrId = StringUtils.join(plugin.getIds(), ",");
    //
    // PluginEntity pluginEntity = pluginService.addLocalPlugin(
    // pluginStrId, plugin.getName(), plugin.getImageFile(), plugin.getDescription(), pluginFolderName, categoryEntity);
    //
    // PluginEntity pluginEntity = pluginDao.getLocalOne(pluginStrId);
    // if (pluginEntity == null) {
    // pluginEntity = new PluginEntity();
    // pluginEntity.setName(plugin.getName());
    // pluginEntity.setPluginId(pluginStrId);
    // pluginEntity.setPluginImage(plugin.getImageFile());
    // pluginEntity.setChargeType(0);
    // pluginEntity.setProfile(plugin.getDescription());
    // pluginEntity.setFuncType(categoryEntity.getFuncType());
    // pluginDao.saveOrUpdate(pluginEntity);
    // }
    //
    // PluginCategoryEntity pluginCategoryEntity = pluginCategoryDao.getOne(pluginEntity.getId(), categoryId);
    // if (pluginCategoryEntity == null) {
    // pluginCategoryEntity = new PluginCategoryEntity();
    // pluginCategoryEntity.setPluginId(pluginEntity.getId());
    // pluginCategoryEntity.setCategoryId(categoryId);
    // pluginCategoryDao.saveOrUpdate(pluginCategoryEntity);
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // }

    // private void updateMarketInfo(ClassificationEntity transMarket, ClassificationEntity jobMarket) throws Exception
    // {
    // String jsonResult = HttpUtil.getString(NetUrl.PLUGIN_MARKET);
    // if (StringUtils.isBlank(jsonResult)) {
    // return;
    // }
    // JSONObject resp = JSONUtil.parseObj(jsonResult);
    // if (!"001000".equals(resp.getStr("code"))) {
    // return;
    // }
    // JSONArray jsonArray = resp.getJSONArray("data");
    // if (jsonArray.isEmpty()) {
    // return;
    // }
    //
    //// // 清除所有旧的数据 方法提前执行, 避免树不更新
    //// // 1, 清理插件信息
    //// pluginService.deleteCloudPlugin();
    ////// pluginDao.deleteCloudPlugin();
    //// // 2, 清理分类信息
    //// categoryService.deleteCloudCategory();
    ////// categoryDao.deleteCloudCategory();
    //
    // for (int i = 0; i < jsonArray.size(); i++) {
    // JSONObject jsonObject = jsonArray.getJSONObject(i);
    // String pluginId = jsonObject.getStr("plugin_meta_id");
    // Integer chargeType = jsonObject.getInt("charge_type");
    // String pluginName = jsonObject.getStr("plugin_name");
    // String pluginProfiles = jsonObject.getStr("plugin_profiles");
    // Long versionId = jsonObject.getLong("version_id");
    // String versionNumber = jsonObject.getStr("version_number");
    // String groupName = jsonObject.getStr("group_name");
    // int funcType = jsonObject.getInt("func_type");
    // String pluginImage = jsonObject.getStr("plugin_image");
    //
    // if (funcType == 1 || funcType == 6) {
    // pluginService.addCloudPlugin(pluginId, pluginName, chargeType, pluginImage, pluginProfiles,
    // versionId.toString(), versionNumber, groupName, StepPluginType.class, transMarket.getId());
    // }
    // if (funcType == 2 || funcType == 6) {
    // pluginService.addCloudPlugin(pluginId, pluginName, chargeType, pluginImage, pluginProfiles,
    // versionId.toString(), versionNumber, groupName, JobEntryPluginType.class, jobMarket.getId());
    // }
    // }
    //
    // }

    // /**
    // * 更新商店插件标签至本地
    // *
    // * @throws Exception
    // */
    // private String getMarketTabInfo() throws Exception {
    // URL url = new URL(Const.MARKET_SERVER_ADDRESS + "/plugin/market/list");
    // URL url = new URL(NetUrl.PLUGIN_MARKET);
    // // URL url = new URL("http://localhost:8099/plugin/market/list");
    // HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // conn.setConnectTimeout(10 * 1000);
    // conn.setRequestProperty("User-Agent", "LaniusDesign");
    // InputStream inputStream = conn.getInputStream();
    // return IOUtils.toString(inputStream, "UTF-8");
    // }
}
